package cn.zl.rtsp;

import cn.zl.rtsp.udp.UDPSocket;
import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.bytedeco.javacv.Frame;
import org.bytedeco.javacv.Java2DFrameConverter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.ByteBuffer;

public class RTPTask implements Runnable {

    private static final Logger logger = LoggerFactory.getLogger(RTPTask.class);

    private boolean running = true;

    private final UDPSocket socket;

    public RTPTask(UDPSocket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        logger.info("RTPTask start");
        while (running) {
            try {
                try (FFmpegFrameGrabber grabber = new FFmpegFrameGrabber("input.h264")){
                    grabber.start();
                    Frame frame;
                    Java2DFrameConverter converter = new Java2DFrameConverter();

                    ByteBuffer buffer = ByteBuffer.allocate(1024); // 分配足够的空间存储NALU和RTP头
                    int sequenceNumber = 0; // RTP序列号
                    long timestamp = System.currentTimeMillis(); // RTP时间戳，可以根据实际情况调整更新频率
                    int ssrc = 12345; // SSRC值，可以根据实际情况设置
                    int payloadType = 96; // H264载荷类型，通常是动态分配的96或97等
                    boolean markerBit = true; // 对于每个NALU的最后一个分片设置M位为1
                    int rtpHeaderSize = 12; // RTP头大小，通常为12字节（不包括载荷部分）
                    int payloadHeaderSize = 1; // H264载荷头部大小，通常为1字节（起始码填充）

                    while ((frame = grabber.grabFrame()) != null) {
                        // 将Frame转换为ByteBuffer，这里假设是H264裸数据流
                        // ByteBuffer frameData = converter.convert(frame); // 这里需要根据实际帧内容调整转换方式
                    }

                    converter.close();
                }

            } catch (Exception e){
                logger.error(e.getMessage(), e);
            }
        }
        logger.info("RTPTask stop");
    }

    public boolean isRunning() {
        return running;
    }

    public void setRunning(boolean running) {
        this.running = running;
    }

}
